// src/client/message_queue.h
#ifndef MESSAGE_QUEUE_H
#define MESSAGE_QUEUE_H

#include <queue>
#include <pthread.h>
#include "../common/message.h"

// 线程安全的消息队列
class MessageQueue {
private:
    std::queue<Message*> messages;
    pthread_mutex_t mutex;
    pthread_cond_t cond_var;

public:
    MessageQueue() {
        pthread_mutex_init(&mutex, nullptr);
        pthread_cond_init(&cond_var, nullptr);
    }
    
    ~MessageQueue() {
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond_var);
        
        // 清理队列中的消息
        while (!messages.empty()) {
            delete messages.front();
            messages.pop();
        }
    }
    
    // 添加消息到队列
    void enqueue(Message* message) {
        pthread_mutex_lock(&mutex);
        messages.push(message);
        pthread_cond_signal(&cond_var); // 通知等待的线程
        pthread_mutex_unlock(&mutex);
    }
    
    // 从队列中取出消息
    Message* dequeue() {
        pthread_mutex_lock(&mutex);
        
        // 等待直到队列中有消息
        while (messages.empty()) {
            pthread_cond_wait(&cond_var, &mutex);
        }
        
        Message* message = messages.front();
        messages.pop();
        
        pthread_mutex_unlock(&mutex);
        return message;
    }
    
    // 检查队列是否为空
    bool empty() {
        pthread_mutex_lock(&mutex);
        bool is_empty = messages.empty();
        pthread_mutex_unlock(&mutex);
        return is_empty;
    }
};

#endif // MESSAGE_QUEUE_H    